package breeze.pixel.weather.apps_util.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.widget.TextView;

import androidx.cardview.widget.CardView;
import androidx.core.content.FileProvider;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import breeze.pixel.weather.App;
import breeze.pixel.weather.BaseView;
import breeze.pixel.weather.R;
import breeze.pixel.weather.apps_util.datas.AppStaticDatas;
import breeze.pixel.weather.apps_util.utils.appsettings.AppSettings;
import breeze.pixel.weather.main_view.view.MainView;
import brz.breeze.app_utils.BHotFixUtils;
import brz.breeze.tool_utils.Blog;

public class AppToolUtil extends AppStaticDatas {

    public static boolean deleteAllPatches(){
        File patchStoragePath = BHotFixUtils.patchStoragePath;
        if (patchStoragePath.exists() && patchStoragePath.listFiles().length > 0){
            File[] files = patchStoragePath.listFiles();
            for (File file1 : files){
                return file1.delete();
            }
        }
        return false;
    }

    public static final String TAG = "AppToolUtil";

    /**
     * @param context，文件夹名称
     * @return 路径
     * @author BREEZE
     * @description 在Android/data/包名/文件夹下创建文件夹
     */
    public static String getFile(Context context, String dirName) {
        return context.getExternalFilesDir(dirName) + "/";
    }

    public static String getTempPicFile(Context context) {
        String s = context.getCacheDir() + "/temp.jpg";
        return s;
    }

    public static String getCacheFile(Context context, String dirName) {
        File file = new File(context.getExternalCacheDir() + File.separator + dirName);
        if (!file.exists()) {
            file.mkdir();
        }
        return file.getAbsolutePath() + File.separator;
    }

    @SuppressLint("SimpleDateFormat")
    public static String getSimpleDate(String format) {
        return new SimpleDateFormat(format).format(System.currentTimeMillis());
    }

    /**
     * @return 星期X
     */
    public static String getDayInWeek() {
        Calendar c = Calendar.getInstance();
        int week_day = c.get(Calendar.DAY_OF_WEEK) - 1;
        if (week_day < 0) {
            week_day = 0;
        }
        return _DATE_WEEK[week_day];
    }

    public static String getDayInWeekOfDate(String time){
        @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        ParsePosition parsePosition = new ParsePosition(0);
        Date parse = simpleDateFormat.parse(time, parsePosition);
        Calendar c = Calendar.getInstance();
        if (parse != null) {
            c.setTime(parse);
            int week_day = c.get(Calendar.DAY_OF_WEEK) - 1;
            if (week_day < 0) {
                week_day = 0;
            }
            return _DATE_WEEK[week_day];
        }
        return null;
    }

    public static void writeDataIntoFile(String content, String filePath) throws IOException {
        FileOutputStream outputStream = new FileOutputStream(filePath);
        byte[] bytes = content.getBytes();
        outputStream.write(bytes);
        outputStream.close();
    }

    public static String getWebCode(String uri) throws IOException {
        URL url = new URL(uri);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        byte[] bytes = new byte[1024];
        int len;
        InputStream inputstream = connection.getInputStream();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        while ((len = inputstream.read(bytes)) != -1) {
            output.write(bytes, 0, len);
        }
        inputstream.close();
        output.close();
        return new String(output.toByteArray(), StandardCharsets.UTF_8);
    }

    public static Bitmap getWebPicture(String uri) throws IOException {
        URL url = new URL(uri);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        InputStream inputStream = connection.getInputStream();
        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
        inputStream.close();
        return bitmap;
    }

    /**
     * @param context       上下文
     * @param picture       图片Bitmap
     * @param filePath，文件路径
     * @author BREEZE
     */
    public static void savePicture(Context context, Bitmap picture, String filePath) throws FileNotFoundException {
        FileOutputStream outputStream = new FileOutputStream(filePath);
        picture.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri img_uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            img_uri = FileProvider.getUriForFile(context, BaseView.getFileProvider(), new File(filePath));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            img_uri = Uri.fromFile(new File(filePath));
        }
        intent.setData(img_uri);
        context.sendBroadcast(intent);
    }

    public static void insertPicture(Context context, Bitmap bitmap) {
        MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmap, getSimpleDate("yyyy-MM-dd HH:mm:ss"), "savedPicture");
    }

    /**
     * @param typeface 字体
     */
    public static void changeGlobalTypeface(Typeface typeface){
        //替换全局的字体
        String[] types = new String[]{"DEFAULT","DEFAULT_BOLD","SANS_SERIF","MONOSPACE","SERIF"};
        for (String str:types){
            try {
                Field filed = Typeface.class.getDeclaredField(str);
                filed.setAccessible(true);
                filed.set(null,typeface);
            } catch (Exception e) {
                Blog.e(TAG,e.toString());
            }
        }
    }

    public static Bitmap getweatherIcon(Context context, String id) {
        Bitmap bitmap;
        try {
            AppSettings sets = AppSettings.getInstance(context);
            if (sets.getIconType() == 0) {
                bitmap = BitmapFactory.decodeStream(context.getResources().getAssets().open("weathericon2/" + id + ".png"));
            } else if (sets.getIconType() == 1) {
                bitmap = BitmapFactory.decodeStream(context.getResources().getAssets().open("weathericon/" + id + ".png"));
            } else if (sets.getIconType() == 2) {
                bitmap = BitmapFactory.decodeStream(context.getResources().getAssets().open("weathericon3/" + id + ".png"));
            } else {
                bitmap = BitmapFactory.decodeStream(context.getResources().getAssets().open("weathericon2/" + id + ".png"));
            }
        } catch (IOException e) {
            e.printStackTrace();
            bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.m999);
        }
        return bitmap;
    }

    public static File getDownloadAPKPath(Context context){
        String s = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/app.apk";
        return new File(s);
    }

    public static void installAPK(String path, Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            File apkFile = new File(path);
            boolean b = App.getContext().getPackageManager().canRequestPackageInstalls();
            if (b) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                Uri uri;
                String type = "application/vnd.android.package-archive";
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    uri = FileProvider.getUriForFile(App.getContext(), App.getFileProvider(), apkFile);
                } else {
                    uri = Uri.fromFile(apkFile);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                }
                intent.setDataAndType(uri, type);
                activity.startActivity(intent);
            } else {
                MDialog mDialog = new MDialog(activity);
                mDialog.setTitle("提示");
                mDialog.setMessage("需打开安装未知应用权限");
                mDialog.setPositiveButton("确定", () -> {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                    activity.startActivity(intent);
                });
                mDialog.setNegativeBotton("取消", null);
                mDialog.show();
            }
        }
    }

    public static String getPicturePath() {
        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/PixelWeather/";
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        return path;
    }

    public static Bitmap getBingPic(final Context mContext) {
        Bitmap bmp = null;
        try {
            String pic_json = AppToolUtil.getWebCode(AppToolUtil._URL_BING_PIC_API);
            JSONArray jsonArray = new JSONObject(pic_json).getJSONArray("images");
            JSONObject obj = jsonArray.getJSONObject(0);
            String url = AppToolUtil._URL_BING_HOST_LINK + obj.getString("url");
            try {
                Bitmap bitmap = AppToolUtil.getWebPicture(url);
                String filePath = AppToolUtil.getCacheFile(mContext, AppToolUtil._PATH_BING_PIC_CACHE_DIR) + AppToolUtil.getSimpleDate(AppToolUtil._DATE_TODAY) + ".png";
                File file = new File(filePath);
                if (!file.exists()) {
                    AppToolUtil.savePicture(mContext, bitmap, filePath);
                }
                bmp = BitmapFactory.decodeFile(filePath);
            } catch (IOException e) {
                Blog.e(TAG, "获取必应图片失败：" + e.toString());
            }
        } catch (Exception e) {
            Blog.e(TAG, "获取必应图片链接失败：" + e.toString());
        }
        return bmp;
    }

    public static int getVerCode(Context context) {
        PackageManager manager = context.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static String getVerName(Context context) {
        PackageManager manager = context.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getMainBackgroundPic(Context context) {
        return getFile(context, "background") + "main_background_pic.png";
    }

    public static String getDrawerBackgroundPic(Context context) {
        return getFile(context, "background") + "drawer_background_pic.png";
    }

    public static String getAppWidgetBackgroundPic_1(Context context) {
        return getFile(context, "background") + "appwidget_background_1_pic.png";
    }

    public static String getAppWidgetBackgroundPic_2(Context context) {
        return getFile(context, "background") + "appwidget_background_2_pic.png";
    }

    public static String getPanelModeBackgroundPic(Context context) {
        return getFile(context, "background") + "panel_mode_background_pic.png";
    }

    public static String getAPKStoragePath(Context context) {
        return getFile(context, "apks") + "app.apk";
    }

    public static String getDiyFontPath(Context context) {
        return getCacheFile(context, "font") + "font.ttf";
    }

    public static void copyFile(final String old, final String newfile) {
        try {
            int byteread;
            File oldfile = new File(old);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(old); //读入原文件
                FileOutputStream fs = new FileOutputStream(newfile);
                byte[] buffer = new byte[1444];
                while ((byteread = inStream.read(buffer)) != -1) {
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void reStartApp(Context context) {
        Intent intent = new Intent(context, MainView.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    public static boolean checkNetwork(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (manager == null) {
            MToast.show(context, "当前没有网络连接噢！");
            return false;
        }
        return true;
    }

    public static void sendBroadcast(Context context, String action) {
        Intent intent = new Intent(action);
        context.sendBroadcast(intent);
    }

    static int _RESULT_CODE = 0;//1:success  -1:fail

    public static int downloadFiles(String fileLink, final String filePath) {
        try {
            URL url = new URL(fileLink);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            InputStream stream = connection.getInputStream();
            int length;
            byte[] bytes = new byte[2048];
            File file = new File(filePath);
            FileOutputStream outputStream = new FileOutputStream(filePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            while ((length = stream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }
            outputStream.close();
            stream.close();
            outputStream.flush();
            _RESULT_CODE = 1;
        } catch (IOException e) {
            e.printStackTrace();
            Blog.e(TAG, "下载失败：" + e.toString());
            _RESULT_CODE = 0;
        }
        return _RESULT_CODE;
    }

    public static Bitmap roundedBitmap(int brightness, Bitmap bitmap, float radius) {
        Bitmap bit = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bit);
        Paint p = new Paint();
        p.setAntiAlias(true);


        Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        RectF rectf = new RectF(rect);
        canvas.drawARGB(0, 0, 0, 0);
        canvas.drawRoundRect(rectf, radius, radius, p);
        p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, p);

        /*RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(App.getContext().getResources(), bitmap);
        roundedBitmapDrawable.setCornerRadius(radius);
        roundedBitmapDrawable.getPaint().setAntiAlias(true);
        Bitmap bit = roundedBitmapDrawable.getBitmap();*/

        Bitmap bmp = Bitmap.createBitmap(bit.getWidth(), bit.getHeight(),
                bit.getConfig());
        ColorMatrix cMatrix = new ColorMatrix();
        cMatrix.set(new float[]{1, 0, 0, 0, brightness, 0, 1,
                0, 0, brightness,// 改变亮度
                0, 0, 1, 0, brightness, 0, 0, 0, 1, 0});

        Paint paint = new Paint();
        paint.setColorFilter(new ColorMatrixColorFilter(cMatrix));

        Canvas canvas2 = new Canvas(bmp);
        // 在Canvas上绘制一个已经存在的Bitmap。这样，dstBitmap就和srcBitmap一摸一样了
        canvas2.drawBitmap(bit, 0, 0, paint);

        return bmp;
    }

    /**
     * @param url 网站
     * @param post 参数
     * @param headers 头部
     * @return 源代码
     * @throws Exception 请求出错
     */
    public static String getWebData(String url, String post, HashMap<String, String> headers) throws Exception {
        URL url1 = new URL(url);
        HttpURLConnection httpURLConnection = (HttpURLConnection)url1.openConnection();
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        if (headers != null) {
            Set<String> strings = headers.keySet();
            Iterator var6 = strings.iterator();

            while(var6.hasNext()) {
                String item = (String)var6.next();
                httpURLConnection.setRequestProperty(item, (String)headers.get(item));
            }
        }

        if (post == null) {
            httpURLConnection.setRequestMethod("GET");
        } else {
            httpURLConnection.setRequestMethod("POST");
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream(), StandardCharsets.UTF_8);
            PrintWriter printWriter = new PrintWriter(outputStreamWriter);
            printWriter.print(post);
            printWriter.flush();
        }

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
        StringBuilder stringBuilder = new StringBuilder();

        String line;
        while((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }

        return stringBuilder.toString();
    }


}
